<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where" @keydown.enter.prevent="reload">
          <a-row style="width: 100%">
            <a-col :span="21">
              <a-form-item>
                客户名称:
                <a-input style="width: 150px;margin-right: 10px;" v-model:value.trim="where.name" placeholder="请输入客户名称" allow-clear />
                客户类型:
                <a-select v-model:value="where.type" placeholder="请选择" style="width: 150px;margin-right: 10px;">
                  <a-select-option value="1">企业客户</a-select-option>
                  <a-select-option value="2">个人客户</a-select-option>
                </a-select>
                代理商:
                <a-select
                  placeholder="请选择"
                  v-model:value="where.agentId"
                  style="width: 150px;margin-right: 10px;"
                  allow-clear>
                  <a-select-option v-for="item in agentList" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
                <a-space>
                  <a-button type="primary" @click="reload">查询</a-button>
                  <a-button @click="reset">重置</a-button>
                </a-space>
              </a-form-item>
            </a-col>
            <!--导出excel-->
            <a-col :span="3">
              <a-form-item class="ele-text-center">
                <a-space>
                  <a-button @click="exportExcel" type="primary" :size="size"
                            style="background-color: rgb(254,108,17);border:rgb(254,108,17);">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    按条件导出
                  </a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="id"
          :datasource="url"
          :columns="columns"
          :where="where"
        >
          <!-- table上边工具栏 -->
<!--          <template #toolbar>
            <a-space>
              &lt;!&ndash;导出excel&ndash;&gt;
              <a-button @click="exportExcel" type="primary" :size="size"
                        style="background-color: rgb(254,108,17);border:rgb(254,108,17);">
                <template #icon>
                  <DownloadOutlined />
                </template>
                按条件导出
              </a-button>
            </a-space>
          </template>-->

          <template #name="{ record }">
            <a-tooltip :title="record.name" placement="topLeft">
              {{ record.name || '--' }}
            </a-tooltip>
          </template>

          <template #address="{ record }">
            <a-tooltip :title="record.address" placement="topLeft">
              {{ record.address || '--' }}
            </a-tooltip>
          </template>

          <template #remark="{ record }">
            <a-tooltip :title="record.remark" placement="topLeft">
              {{ record.remark || '--' }}
            </a-tooltip>
          </template>

          <template #typeName="{ record }">
            <ele-tag v-if="record.typeName === '企业客户'" size="mini" color="blue">{{ record.typeName }}</ele-tag>
            <ele-tag v-if="record.typeName === '个人客户'" size="mini" color="green">{{ record.typeName }}</ele-tag>
          </template>

          <!-- table列表状态栏 -->
          <!-- 1是激活，2是禁用 -->
          <template #state="{ record }">
            <a-switch :checked="record.statusFlag === 1" @change="checked => editState(checked, record)" />
          </template>

          <!-- table操作栏按钮 -->
          <template #action="{ record }">
            <a-space>
              <a @click="openDetail(record)">详情</a>
<!--              <a @click="openEdit(record)" v-if="user.roleId !== '2'">变更代理商</a>-->
<!--              <a-divider type="vertical" />
              <router-link :to="{ name: '/customer/contacts', params: {  customerName: record.name } }"
                           class="ele-text-danger">联系人
              </router-link>-->
              <!--              <a-popconfirm title="确定要重置此账号密码吗？" @confirm=" resetPassword(record)">
                              <a class="ele-text-danger">联系人</a>
                            </a-popconfirm>-->
            </a-space>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
  </div>

  <!-- 编辑弹窗 -->
  <info-edit v-model:visible="showEdit" :data="current" @done="reload" />
  <!-- 详情弹窗 -->
  <info-detail v-model:visible="showDetail" :data="current" @done="reload" />
</template>

<script>
import { onMounted, ref } from 'vue';
// 删除，感叹号，加号图标
import InfoEdit from './info-edit.vue';
import InfoDetail from './info-detail.vue';
import { CustomerApi } from '@/api/CustomerApi';
import { AgentApi } from '@/api/AgentApi';
import { utils, writeFile } from 'xlsx';
import { DashboardApi } from '@/api/DashboardApi';

export default {
  name: 'customer_info',
  components: {
    InfoEdit,
    InfoDetail
  },

  setup() {

    // 加载代理商下拉数据
    const agentList = ref([]);

    async function fetchAgentList() {
      const res = await AgentApi.findList({});
      agentList.value = res.data;
    }

    // 页面初次挂载时加载下拉数据
    onMounted(async () => {
      await fetchAgentList();
    });

    return {
      agentList
    };
  },

  data() {
    return {
      // 用户信息
      user: {},
      // 表格数据接口
      url: '/business/api/customer/info/findPage',
      // 表格列配置
      columns: [
        {
          title: '序号',
          key: 'index',
          width: 48,
          customRender: ({ index }) => this.$refs.table.tableIndex + index
        },
        {
          title: '客户名称',
          dataIndex: 'name',
          width: 200,
          sorter: false,
          ellipsis: true,
          slots: { customRender: 'name' }
        },
        {
          title: '客户类型',
          dataIndex: 'typeName',
          width: 120,
          sorter: false,
          slots: { customRender: 'typeName' }
        },
        {
          title: '所在地区',
          dataIndex: 'address',
          width: 160,
          sorter: false,
          ellipsis: true,
          slots: { customRender: 'address' }
        },
        {
          title: '所属代理商',
          dataIndex: 'agentName',
          width: 160,
          sorter: false
        },
        /*{
          title: '备注',
          dataIndex: 'remark',
          key: 'remark',
          width: 200,
          ellipsis: true,
          slots: { customRender: 'remark' }
        },
        {
          title: '操作时间',
          dataIndex: 'updateTime',
          sorter: true,
          width: 160
        },*/
        {
          title: '状态',
          dataIndex: 'customerStatusName',
          sorter: false,
          width: 160
        },
        /*{
          title: '状态',
          dataIndex: 'status',
          sorter: false,
          align: 'center',
          width: 120,
          slots: { customRender: 'state' }
        },*/
        {
          title: '操作',
          key: 'action',
          width: 190,
          fixed: 'right',
          align: 'center',
          slots: { customRender: 'action' }
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 是否显示详情弹窗
      showDetail: false
    };
  },
  mounted() {
    this.getUser();
  },
  methods: {
    // 获取用户信息
    async getUser() {
      const res = await DashboardApi.getUser();
      this.user = res.data;
    },
    /**
     * 搜索按钮
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     */
    reset() {
      this.where = {};
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除单个
     */
    async remove(row) {
      const result = await CustomerApi.del({ id: row.id });
      this.$message.success(result.message);
      this.reload();
    },

    /**
     * 打开详情弹窗
     */
    openDetail(row) {
      this.current = row;
      this.showDetail = true;
    },

    /**
     * 打开编辑弹窗
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },

    /**
     * 修改状态
     */
    async editState(checked, row) {
      const id = row.id;
      // 状态：1-启用，2-禁用
      const statusFlag = checked ? 1 : 2;
      const result = await CustomerApi.edit({ id, statusFlag });
      this.$message.success(result.message);
      row.statusFlag = statusFlag;
    },
    exportExcel() {
      this.loading = true;
      const exportWhere = {
        ...this.where,
        pageNo: 1,
        pageSize: 10000
      };

      CustomerApi.findPage(exportWhere).then((res) => {
        let data = res.data.rows;
        let array = [
          [
            '客户名称',
            '客户类型',
            '所在地区',
            '所属代理商',
            '备注',
            '操作时间',
            '状态'
          ]
        ];
        data.forEach((d) => {
          if (d.statusFlag === 1) {
            d.statusFlag = '启用';
          } else {
            d.statusFlag = '禁用';
          }
          array.push([
            d.name,
            d.typeName,
            d.address,
            d.agentName,
            d.remark,
            d.updateTime,
            d.statusFlag
          ]);
        });
        writeFile(
          {
            SheetNames: ['客户信息'],
            Sheets: {
              客户信息: utils.aoa_to_sheet(array)
            }
          },
          '客户信息.xlsx'
        );
        this.loading = false;
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    }
  }
};
</script>

<style scoped>
/*搜索框与表格之间的间隙*/
.block-interval {
  margin-bottom: 10px;
}

/*重写顶部搜索表单的样式*/
.ant-form-item {
  margin-bottom: 0;
}
/* 表格斑马样式 **/
/deep/.ant-table-tbody tr:nth-child(2n)
{
  background-color:#fafafa;
}
</style>
